<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!config('requestLog.enabled')) {
            return $next($request);
        }
        $log = new \App\Models\RequestLog(); // 日志表
        $log->url = $request->fullUrl();
        $params = json_encode($request->all(), JSON_UNESCAPED_UNICODE);
        if ($request->route()->uri == 'api/v1/authorizations') {
            $params = json_encode($request->only('name'), JSON_UNESCAPED_UNICODE);
        }
        $log->ip = $request->getClientIp();
        $log->params = $params;
        $log->user_id = auth('api')->user()->id ?? 0;
        $log->save();
        $response = $next ($request);
        if ($rep = $response->getContent()) {
            $log->update([
                'response' => $rep,
                'duration' => get_all_duration(),
            ]);
        }
        return $response;
    }
}
